import "./register.css";
import useForm from "@module/useForm";
import Input from "@ui/RJMart/input";
import Icon from "@ui/RJMart/icons";
import RobinFilter from "@module/RobinFilter";
import ZenUI from "@root/components/ZenUI/ZenUI";
import usePartState from "@module/usePartState";
import message from "@ui/RJMart/message";

export default function StepThree(props) {
    const params = $state.params;
    const { key, registerType, email, token } = params || {};

    React.useEffect(() => {
        params.registerType == 1 ? verificationEmail() : CheckToken();
    }, []);

    const [stateObj, updateState] = usePartState({
        canClickVerifyBtn: false,
        showPage: false
    });

    function doSubmit() {
        const isValid = formData.$$valid;
        if (isValid) {
            ZenUI.SL(60);

            if (params.registerType == 1) {
                //校验验证码
                let checkUrl = `/store/api/invite/verificationPin`;
                let checkData = {
                    mobile: formData.phone,
                    pin: formData.code
                };
                let headerConfig = {
                    contentType: 1
                };
                REST.post(checkUrl, checkData, "dis", headerConfig).then(
                    function(data) {
                        console.log(data);
                        if (data.code == "0000") {
                            doRegister();
                        } else {
                            ZenUI.HL();
                            updateFormData({
                                $$status: { code: data.message, phone: "" }
                            });
                        }
                    },
                    function(error) {
                        ZenUI.HL();
                        console.log(error);
                    }
                );
            } else if (params.registerType == 2) {
                doRegister();
            }
        }
    }

    function doRegister() {
        let regUrl, regData;
        if (params.registerType == 1) {
            regUrl = `/store/api/invite/register`;
            regData = {
                email: params.email,
                mobilePhone: formData.phone,
                userName: formData.username,
                orgName: formData.orgName,
                departName: formData.departName,
                approvedWay: formData.approvedWay, //0自动审批，1手动审批
                token: params.token,
                devType: 1 //0移动端，1PC端
            };
        } else if (params.registerType == 2) {
            regUrl = "/suppliers/anon/SupplierActivate";
            regData = {
                email: params.email,
                mobile: formData.phone,
                name: formData.username,
                pin: formData.code,
                token: params.token
            };
        }
        REST.post(regUrl, regData, "dis").then(
            function(data) {
                ZenUI.HL();
                console.log(data);
                if (data.code == "0000") {
                    doStepThree();
                } else {
                    // alert(data.message);
                    if (params.registerType == 1) {
                        if (
                            data.message.indexOf("&lt;") > -1 ||
                            data.message.indexOf("&gt;") > -1
                        ) {
                            let tmp1 = data.message.replace("&lt;", "<");
                            let tmp2 = tmp1.replace("&gt;", ">");
                            data.message = tmp2;
                        }
                        updateState({ errorInfo: data.message });
                    } else if (params.registerType == 2) {
                        updateFormData({
                            $$status: { code: data.message }
                        });
                    }
                }
            },
            function(error) {
                ZenUI.HL();
                console.log(error);
            }
        );
    }

    function doStepThree() {
        $state.go({
            stateName: "/register",
            params: {
                step: 4,
                registerType: params.registerType
            }
        });
    }

    function verificationEmail() {
        ZenUI.SL(60);
        let vftUrl = `/store/api/invite/verificationEmail`;
        let vftData = {
            email: params.email,
            token: params.token
        };
        let headerConfig = {
            contentType: 1
        };
        REST.post(vftUrl, vftData, "noInfo", headerConfig).then(
            function(data) {
                ZenUI.HL();
                console.log(data);
                if (data.code == "0000") {
                    updateState({ showPage: true });
                } else {
                    message.info(data.message);
                }
            },
            function(error) {
                ZenUI.HL();
                console.log(error);
            }
        );
    }

    function CheckToken() {
        ZenUI.SL(60);
        let ctUrl = "/suppliers/anon/CheckToken";
        let ctData = {
            account: params.email,
            token: params.token
        };
        REST.post(ctUrl, ctData, "noInfo").then(
            function(data) {
                ZenUI.HL();
                console.log(data);
                if (data.code == "0000") {
                    updateState({ showPage: true });
                } else {
                    message.info(data.message);
                }
            },
            function(error) {
                ZenUI.HL();
                console.log(error);
            }
        );
    }

    const {
        formData,
        handleChange,
        handleSubmit,
        updateFormData,
        validations,
        addValidate,
        addValidateMulti
    } = useForm(
        doSubmit,
        { registerType: params.registerType },
        "regiFormStep3"
    );

    function phoneValidate(value) {
        let res = RobinFilter.phoneValidate(value);
        if (res) {
            updateState({ canClickVerifyBtn: false });
            return res;
        }
        updateState({ canClickVerifyBtn: true });
        return "";
    }

    addValidateMulti({
        username: [],
        phone: [phoneValidate],
        code: [RobinFilter.verifyCodeValidate]
    });

    function beforeHandleChange(event) {
        handleChange(event);
        // console.log(formData)
    }

    return (
        <form
            className={"regi-content-form zen_p-b-80 zen_m-t-40"}
            name={"regiFormStep3"}
        >
            {stateObj.showPage && (
                <div>
                    <InputItem
                        name={"username"}
                        title={"真实姓名"}
                        placeholder={"请输入真实姓名"}
                        handleChange={beforeHandleChange}
                        formData={formData}
                    />

                    <InputItem
                        name={"phone"}
                        title={"手机号码"}
                        placeholder={"用于账户验证，请务必正确填写"}
                        handleChange={beforeHandleChange}
                        formData={formData}
                    />

                    <InputItemForVerifyCode
                        name={"code"}
                        title={"手机验证码"}
                        placeholder={"请输入验证码"}
                        handleChange={beforeHandleChange}
                        formData={formData}
                        updateFormData={updateFormData}
                        index={3}
                        canClickVerifyBtn={stateObj.canClickVerifyBtn}
                    />

                    {params.registerType == 1 && (
                        <InputItem
                            name={"orgName"}
                            title={"所属单位"}
                            placeholder={"请填写完整的单位名称"}
                            handleChange={beforeHandleChange}
                            formData={formData}
                        />
                    )}

                    {params.registerType == 1 && (
                        <InputItem
                            name={"departName"}
                            title={"课题组名"}
                            placeholder={"请填写完整的课题组名"}
                            handleChange={beforeHandleChange}
                            formData={formData}
                        />
                    )}

                    {params.registerType == 1 && (
                        <div className="regi-content-inputs">
                            <div className="regi-step3-label-box">
                                <span className={"regi-content-required"}>
                                    *
                                </span>
                                <span>审批方式</span>
                            </div>
                            <div className="regi-inputs-input zen_h-40 zen_l-h-40 a-approvedWay">
                                <span className="zen_m-r-30">
                                    <input
                                        type="radio"
                                        name="approvedWay"
                                        value="0"
                                        checked="checked"
                                    />
                                    {" 自动审批"}
                                </span>
                                <span>
                                    <input
                                        type="radio"
                                        name="approvedWay"
                                        value="1"
                                    />
                                    {" 手动审批"}
                                </span>
                            </div>
                        </div>
                    )}

                    {params.registerType == 1 && stateObj.errorInfo && (
                        <div className="regi-content-inputs">
                            <p className={"regi-content-error-tip"}>
                                {stateObj.errorInfo}
                            </p>
                        </div>
                    )}

                    <NextStep
                        doSubmit={doSubmit}
                        formData={formData}
                        type={params.registerType}
                    />
                </div>
            )}
        </form>
    );
}

function InputItem(props) {
    const { title, placeholder, index, handleChange, name } = props;
    let formData = props.formData;

    function addName() {
        let inputEle = document.querySelector(
            `.regi-inputs-input>div[name=${name}] input`
        );
        if (inputEle) {
            inputEle.setAttribute("name", name);
        }
    }

    React.useEffect(() => {
        addName();
    }, []);

    const isValid =
        formData.$$status.hasOwnProperty(name) && formData.$$status[name]
            ? false
            : true;

    return (
        <div className={"regi-content-inputs"}>
            <div
                className={
                    index == 3
                        ? "regi-step3-label-box2"
                        : "regi-step3-label-box"
                }
            >
                <span className={"regi-content-label"}>{title}</span>
            </div>
            <div className={"regi-inputs-input"}>
                <Input
                    name={name}
                    placeholder={placeholder}
                    onChange={handleChange}
                    error={!isValid}
                    statusIcon={
                        isValid ? null : (
                            <Icon
                                type="exclamation-circle-fill"
                                color="error"
                                width="18.26px"
                                height="18.26px"
                            />
                        )
                    }
                />

                {!isValid && (
                    <p className={"regi-content-error-tip"}>
                        {formData.$$status[name]}
                    </p>
                )}
            </div>
        </div>
    );
}

let unclickable = false;
function InputItemForVerifyCode(props) {
    const [stateObj, updateState] = usePartState({
        verifyTxt: "获取验证码",
        hasTimer: false
    });
    const {
        title,
        placeholder,
        index,
        handleChange,
        name,
        canClickVerifyBtn,
        updateFormData
    } = props;
    let formData = props.formData;
    // console.log(formData);

    function addName() {
        let inputEle = document.querySelector(
            `.regi-inputs-input>div[name=${name}] input`
        );
        if (inputEle) {
            inputEle.setAttribute("name", name);
        }
    }

    React.useEffect(() => {
        addName();
    }, []);

    let timerId = null;
    function getVerifycode() {
        const isValid =
            formData.$$status.hasOwnProperty("phone") &&
            !formData.$$status["phone"]
                ? true
                : false;
        console.log(isValid);

        if (unclickable) {
            updateFormData({
                $$status: { code: "手机验证码请求太频繁，请稍后再试" }
            });
            return false;
        }

        if (isValid) {
            let codeUrl = "/store/api/system/PinRequest";
            let codeData = {
                mobile: formData.phone,
                useraction: "BuyerRegister"
            };
            if (formData.registerType == 2) {
                codeUrl = "/suppliers/anon/pinRequest";
                codeData.useraction = "SuppActivate";
            }
            REST.post(codeUrl, codeData, "dis").then(
                function(data) {
                    console.log(data);
                    if (data.code == "0000") {
                        console.log("获取验证码成功");
                        countDown(); //倒计时
                    } else if (data.code == "1012" || data.code == "1013") {
                        unclickable = true;
                        updateFormData({
                            $$status: { code: data.message }
                        });
                    } else {
                        // alert(data.message);
                        updateFormData({
                            $$status: { code: data.message }
                        });
                    }
                },
                function(error) {
                    console.log(error);
                }
            );
        }
    }

    function countDown() {
        let seconds = 60;
        updateState({
            verifyTxt: `剩 ${seconds} 秒`,
            hasTimer: true
        });
        timerId = setInterval(() => {
            if (seconds <= 1) {
                updateState({
                    verifyTxt: `获取验证码`,
                    hasTimer: false
                });
                clearInterval(timerId);
                return;
            }
            seconds--;
            updateState({
                verifyTxt: `剩 ${seconds} 秒`,
                hasTimer: true
            });
        }, 1000);
    }

    const isValid =
        formData.$$status.hasOwnProperty(name) && formData.$$status[name]
            ? false
            : true;

    return (
        <div className={"regi-content-inputs"}>
            <div
                className={
                    index == 3
                        ? "regi-step3-label-box2"
                        : "regi-step3-label-box"
                }
            >
                <span className={"regi-content-label"}>{title}</span>
            </div>
            <div className={"regi-inputs-input"}>
                <Input
                    name={name}
                    placeholder={placeholder}
                    onChange={handleChange}
                    error={!isValid}
                    statusIcon={
                        isValid ? null : (
                            <Icon
                                type="exclamation-circle-fill"
                                color="error"
                                width="18.26px"
                                height="18.26px"
                            />
                        )
                    }
                />
                {canClickVerifyBtn ? (
                    <div
                        onClick={stateObj.hasTimer ? () => {} : getVerifycode}
                        className={
                            stateObj.hasTimer
                                ? "regi-step3-veri3"
                                : "regi-step3-veri2"
                        }
                    >
                        <p>{stateObj.verifyTxt}</p>
                    </div>
                ) : (
                    <div className={"regi-step3-veri"}>
                        <p>获取验证码</p>
                    </div>
                )}

                {!isValid && (
                    <p className={"regi-content-error-tip"}>
                        {formData.$$status[name]}
                    </p>
                )}
            </div>
        </div>
    );
}

function NextStep(props) {
    const { doSubmit, formData, type } = props;
    const isValid = formData.$$valid;
    return (
        <div
            onClick={doSubmit}
            className={
                isValid ? "regi-content-next-step" : "regi-content-next-step1"
            }
        >
            <p>{type == 1 ? "提交审核" : "完成"}</p>
        </div>
    );
}
